package azalea.mqtt.gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.BoxLayout;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;

//TODO 取消订阅，qos设置，复制到剪贴板，发送消息的回应处理
//TODO list 响应上下键盘选择
public class MainApp {
	static MainApp window;

	private JFrame frame;
	JTabbedPane tabbedPane;
	ListModel listModel = new ListModel();
	JList<MqttClientModel> list;
	private JPanel panel_1;
	Image imageICO;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		try {
			// 设置 Windows 风格 Look and Feel
			UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
		} catch (Exception e) {
			// 如果设置失败，打印异常信息
			e.printStackTrace();
		}
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					window = new MainApp();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public MainApp() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		loadImage();
		loadHistory();
		frame = new JFrame();
		frame.setTitle("MQTT3.1.1客户端");
		frame.setBounds(100, 100, 1058, 551);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().setLayout(new BorderLayout(0, 0));
		frame.setIconImage(imageICO);

		JPanel panel = new JPanel();
		panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
		panel.setBackground(Color.WHITE);
		frame.getContentPane().add(panel, BorderLayout.WEST);
		frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
		frame.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				window.showExitConfirmation(frame);
			}
		});
		list = new JList<MqttClientModel>(listModel);
		list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		setupDeleteAction(list, listModel);
		list.setLayoutOrientation(JList.VERTICAL);
		list.setBackground(Color.white);
		list.setCellRenderer(new DefaultListCellRenderer() {
			private static final long serialVersionUID = 8841304539624068785L;

			@Override
			public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected,
					boolean cellHasFocus) {

				Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
				if (value instanceof String) {
					// 添加水果图标
					Icon icon = getFruitIcon((String) value);
					setText((String) value);
					setIcon(icon);
				} else if (value instanceof MqttClientModel) {
					Icon icon = getFruitIcon(null);
					setText(((MqttClientModel) value).getClientName());
					setIcon(icon);
				}
				return c;
			}
		});

		list.addListSelectionListener(e -> {
			if (!e.getValueIsAdjusting()) {
				// System.out.println("选中项变化: " + list.getSelectedValuesList());
				java.util.List<MqttClientModel> selected = list.getSelectedValuesList();
				String connName = selected.get(0).getClientName();
				boolean find = findTab(connName);
				if (!find) {
					addNewConnByName(connName);
				}
			}
		});

		panel_1 = new JPanel();
		panel.add(panel_1);

		JButton btnNewButton = new JButton("新连接");
		panel_1.add(btnNewButton);
		panel_1.setPreferredSize(new Dimension(100, 30));
		panel_1.setMinimumSize(new Dimension(100, 30));
		panel_1.setMaximumSize(new Dimension(Short.MAX_VALUE, 30));
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				addNewConn();
			}
		});

		panel.add(list);

		tabbedPane = new JTabbedPane(JTabbedPane.TOP);
		frame.getContentPane().add(tabbedPane, BorderLayout.CENTER);
	}

	private void setupDeleteAction(JList<MqttClientModel> list2, ListModel listModel2) {
		InputMap inputMap = list.getInputMap(JComponent.WHEN_FOCUSED);
		ActionMap actionMap = list.getActionMap();

		// 定义删除键的键绑定
		KeyStroke deleteKey = KeyStroke.getKeyStroke("DELETE");
		inputMap.put(deleteKey, "deleteAction");

		// 创建删除动作
		actionMap.put("deleteAction", new AbstractAction() {
			@Override
			public void actionPerformed(ActionEvent e) {
				int selectedIndex = list.getSelectedIndex();
				if (selectedIndex < 0) {
					return;
				}
				java.util.List<MqttClientModel> selected = list.getSelectedValuesList();
				String connName = selected.get(0).getClientName();
				boolean find = findTab(connName);
				if (find) {
					JOptionPane.showMessageDialog(frame, "删除前必须先关闭tab页", "错误", JOptionPane.ERROR_MESSAGE);
					return;
				}
				int result = JOptionPane.showConfirmDialog(frame, "确定要删除吗？", "确认删除", JOptionPane.YES_NO_OPTION,
						JOptionPane.QUESTION_MESSAGE);
				if (result == JOptionPane.YES_OPTION) {
					listModel.remove(selectedIndex);
				}
			}
		});
	}

	private void addNewConn() {
		NewConnDlg dialog = new NewConnDlg(this);
		dialog.setModal(true);
		dialog.setVisible(true);
		// tabbedPane.add(new MqttClientPanel());
	}

	public void addNewConnByName(String connName) {
		if (GlobalCompMap.getInstance().get(connName) != null) {
			return;
		}
		MqttClientModel model = null;
		for (int i = 0; i < listModel.getSize(); ++i) {
			if (Objects.equals(listModel.get(i).getClientName(), connName)) {
				model = listModel.get(i);
			}
		}
		if (model == null) {
			model = new MqttClientModel();
			model.setClientName(connName);
			listModel.addElement(model);
		} else {

		}
		MqttClientPanel mqttpanel = new MqttClientPanel(this, connName);
		tabbedPane.add(connName, mqttpanel);
		mqttpanel.initByModel(model);
		GlobalCompMap.getInstance().put(connName, mqttpanel);
		int index = tabbedPane.getTabCount() - 1;
		tabbedPane.setTabComponentAt(index, new ClosableTabComponent(tabbedPane, tabbedPane.getTitleAt(index), index));
	}

	private Icon getFruitIcon(String fruit) {
		// 实际项目中应加载真实图标
		ImageIcon ico = new ImageIcon(imageICO); // 空图标占位
		return ico;
	}

	private void loadImage() {
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		InputStream inputStream = classLoader.getResourceAsStream("images/mqtt.png");
		try {
			imageICO = ImageIO.read(inputStream);
			imageICO = imageICO.getScaledInstance(16, 16, Image.SCALE_SMOOTH);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
		}
	}

	public void saveHistory() {
		String path = "azalea.his";
		SerializationUtils.serializeToFile(listModel, path);
	}

	public void loadHistory() {
		try {
			String path = "azalea.his";
			if (!(new File(path)).exists()) {
				return;
			}
			DefaultListModel<MqttClientModel> loadListModel = (DefaultListModel<MqttClientModel>) SerializationUtils
					.deserializeFromFile(path);
			listModel.clear();
			for (int i = 0; i < loadListModel.size(); ++i) {
				listModel.add(i, loadListModel.get(i));
			}
		} catch (Exception e) {

		}

	}
	// TODO ,持久化，反序列化

	public void synClientInfo(MqttClientModel mqttClientModel) {
		// TODO Auto-generated method stub
		if (mqttClientModel == null) {
			return;
		}
		boolean find = false;
		for (int i = 0; i < listModel.size(); ++i) {
			MqttClientModel current = listModel.get(i);
			if (Objects.equals(current.getClientName(), mqttClientModel.getClientName())) {
				find = true;
				current.setClientId(mqttClientModel.getClientId());
				current.setHost(mqttClientModel.getHost());
				current.setPassword(mqttClientModel.getPassword());
				current.setPort(mqttClientModel.getPort());
				current.setUserName(mqttClientModel.getUserName());
				current.setKeepLive(mqttClientModel.getKeepLive());
				current.setTopic(mqttClientModel.getTopic());
				current.setQos(mqttClientModel.getQos());
				break;
			}
		}
		if (!find) {
			// 新增？？？
		}
	}

	private void showExitConfirmation(JFrame frame) {
		int result = JOptionPane.showConfirmDialog(frame, "确定要退出程序吗？", "确认退出", JOptionPane.YES_NO_OPTION,
				JOptionPane.QUESTION_MESSAGE);

		if (result == JOptionPane.YES_OPTION) {
			// 执行退出前的清理工作
			window.cleanupBeforeExit(frame);
			System.exit(0);
		}
	}

	private void cleanupBeforeExit(JFrame frame2) {
		saveHistory();
	}

	private boolean findTab(String name) {
		boolean find = false;
		for (int i = 0; i < tabbedPane.getTabCount(); ++i) {
			String title = tabbedPane.getTitleAt(i);
			if (Objects.equals(title, name)) {
				find = true;
				break;
			}
		}
		return find;
	}
}
